﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using CpuUsageAPI;

namespace ProcessManager
{
    public partial class FrmMain : Form
    {
        private ProcessProvider provider;

        public FrmMain()
        {
            InitializeComponent();
            provider = new ProcessProvider();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //读取监视器本身配置
            provider.ConfigProcesses();
            BindProGridData();

            statusLabel1.Text = string.Format("Status:极限Cpu占用率{0}%    极限内存占用{1}K    {2}次检测无变化重启进程"
                , provider.LimitCpuUsage, provider.LimitMemSize, provider.FixedTimes);
        }

        private void BindProGridData()
        {
            dataGridView1.Rows.Clear();
            foreach (var p in provider.ProInfoList)
            {
                DataGridViewRow row = new DataGridViewRow();
                int n = dataGridView1.Rows.Add();
                row = dataGridView1.Rows[n];
                row.Cells[ColProId.Name].Value = p.ProId;
                row.Cells[ColCpuUsage.Name].Value = p.CpuUsage;
                row.Cells[ColMemSize.Name].Value = p.PhysicalMemSize;
                row.Cells[ColFilePath.Name].Value = p.FilePath;
            }
        }

        private void AppendRencentLog(string str)
        {
            if (txtRecentLogs.Text.Length > 5000)
            {
                //超过5000个字符就清空
                txtRecentLogs.Text += string.Format("{0}:{1}\r\n"
                    , DateTime.Now, str);
            }
        }

        /// <summary>
        /// 检查被监视的进程状态，出现异常情况自动重启
        /// </summary>
        private void CheckProcessStatus()
        {
            for (int i = 0; i < provider.ProInfoList.Count; i++)
            {
                if (provider.ProInfoList[i].CpuUsageFixedTimes > provider.FixedTimes
                    || provider.ProInfoList[i].MemSizeFixedTimes > provider.FixedTimes
                    || provider.ProInfoList[i].CpuUsage > provider.LimitCpuUsage
                    || provider.ProInfoList[i].PhysicalMemSize > provider.LimitMemSize)
                {
                    provider.ShutProcess(provider.ProInfoList[i]);
                    LogHelper.WriteLog(string.Format("进程{0}运行异常，准备重新启动", provider.ProInfoList[i].ProId));
                    AppendRencentLog(string.Format("进程{0}运行异常，准备重新启动", provider.ProInfoList[i].ProId));
                    Thread.Sleep(1000);
                    //此处Load各外挂程序的配置文件
                    //proProvider.ProInfoList[i].PlugConfig.Build();
                    Process p = UIAutomation.UIAutomation.StartApplication(provider.ProInfoList[i].FilePath, true, 1000);
                    if (p != null)
                    {
                        provider.ProInfoList[i].ProId = p.Id;
                        provider.ProInfoList[i].Name = p.ProcessName;
                        provider.ProInfoList[i].StartTime = p.StartTime;
                        provider.ProInfoList[i].CpuUsageFixedTimes = 0;
                        provider.ProInfoList[i].MemSizeFixedTimes = 0;

                        LogHelper.WriteLog(string.Format("启动了程序{0}，进程ID为{1}"
                            , provider.ProInfoList[i].FilePath, p.Id));
                        AppendRencentLog(string.Format("启动了程序{0}，进程ID为{1}"
                            , provider.ProInfoList[i].FilePath, p.Id));
                    }
                }
            }
        }

        private void btnStartAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < provider.ProInfoList.Count; i++)
            {
                //关闭所有路径相同的程序
                provider.ShutProcess(provider.ProInfoList[i]);

                //此处Load各外挂程序的配置文件
                //proProvider.ProInfoList[i].PlugConfig.Build();
                Process p = UIAutomation.UIAutomation.StartApplication(provider.ProInfoList[i].FilePath, true, 1000);
                if (p != null)
                {
                    provider.ProInfoList[i].ProId = p.Id;
                    provider.ProInfoList[i].Name = p.ProcessName;
                    provider.ProInfoList[i].StartTime = p.StartTime;
                    provider.ProInfoList[i].CpuUsageFixedTimes = 0;
                    provider.ProInfoList[i].MemSizeFixedTimes = 0;

                    LogHelper.WriteLog(string.Format("启动了程序{0}，进程ID为{1}"
                        , provider.ProInfoList[i].FilePath, p.Id));
                    AppendRencentLog(string.Format("启动了程序{0}，进程ID为{1}"
                           , provider.ProInfoList[i].FilePath, p.Id));
                }
            }

            timer1.Interval = 1000;
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            provider.UpdateAllProcessCpuUsage();
            BindProGridData();
            CheckProcessStatus();
        }
    }
}
